<?php
/**
 * Author: yann
 * QQ: 9197313
 * Date: 2018/11/26 0026
 * Time: 下午 6:05
 */

namespace app\api\controller;
use app\model\Token;
use app\util\ReturnCode;
use think\Controller;


class Base extends Controller
{
    private $debug = [];
    protected $appid = 'wx15ccaeb7366b1ebf';
    protected $appsecret = '4bafc2be4b2324f93d34ac48f33ad714';

    public function initialize(){
        $action = $this->request->action();
        $token = $this->request->header('Authorization','');

        if(!$this->checkLoginStatus() && $token && $action!= 'login' && $action!= 'openlottery')
            $this->checkToken();
    }

    protected function buildSuccess($data, $msg = '操作成功', $code = ReturnCode::SUCCESS) {
        $return = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data
        ];
        if ($this->debug)
            $return['debug'] = $this->debug;

        return json_encode($return);
    }

    protected function buildFailed($code, $msg, $data = []) {
        $return = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data
        ];
        if ($this->debug)
            $return['debug'] = $this->debug;

        return json_encode($return);
    }

    protected function debug($data) {
        if ($data)
            $this->debug[] = $data;
    }

    private function checkLoginStatus(){
        return session('openid');
    }

    private function checkToken(){
        $token = $this->request->header('Authorization','');
        if(!$token)
            exit($this->buildFailed(ReturnCode::ACCESS_TOKEN_TIMEOUT,'非法的token'));
        try {
            $res = Token::where(['token' => $token])->find();
            if(time() > $res['expire_time'])
                exit($this->buildFailed(ReturnCode::ACCESS_TOKEN_TIMEOUT,'token已过期'));
            session('openid', $res['openid']);
        } catch (\Exception $e) {
            exit($this->buildFailed(ReturnCode::ACCESS_TOKEN_TIMEOUT,'非法的token'));
        }
    }

    protected function buildPaging($record_count = 1, $page = 1 ,$size = 10){
        $record_count = intval($record_count);
        $page = intval($page);
        $size = intval($size);
        $page_count = ($record_count > 0) ? intval(ceil($record_count / $size)) : 1;
        $paging = [
            'page' => $page,
            'size' => $size,
            'record_count' => $record_count,
            'page_count' => $page_count,
            'page_start' => ($page - 1) * $size,
        ];
        return $paging;
    }

    protected function httpGet($url,$data) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    protected function getAccessToken() {
        $data = cache('access_token_json_'.$this->appid);
        if ($data['expire_time'] < time()) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->appsecret";
            $res = json_decode($this->httpGet($url,null));
            $access_token = $res->access_token;

            if ($access_token) {
                $data['expire_time'] = time() + 7100;
                $data['access_token'] = $access_token;
                cache('access_token_json_'.$this->appid,$data);
            }
        } else {
            $access_token = $data['access_token'];
        }
        return $access_token;
    }
}
